﻿/*
-----------------------------------------------------------------------------
This source file is part of Cell Cloud.

Copyright (c) 2009-2012 Cell Cloud Team - cellcloudproject@gmail.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

#include "CellStableHeaders.h"
#include "CellSingleFileStorage.h"
#include "CellSchema.h"
#include "CellFileUtil.h"
#include "CellString.h"
#include "CellStringConverter.h"

namespace cell
{

/// 缓冲截取值，默认 1MB
#define SFS_FETCH_SIZE 1048576

//---------------------------------------------------------------------------
const String SingleFileStorage::FIELD_EXIST = "exist";
const String SingleFileStorage::FIELD_DATA = "data";
const String SingleFileStorage::FIELD_SIZE = "size";

//---------------------------------------------------------------------------
SingleFileStorage::SingleFileStorage(const String& name)
	: Storage(name)
	, mFetchSize(SFS_FETCH_SIZE)
	, mFileSize(0)
	, mMaxFetchNum(16)
	, mReadBuffer(NULL)
	, mTotalLength(0)
{
}
//---------------------------------------------------------------------------
SingleFileStorage::~SingleFileStorage(void)
{
	if (NULL != mReadBuffer)
	{
		CELL_DELETE mReadBuffer;
		mReadBuffer = NULL;
	}

	if (!mSFSBuffers.empty())
	{
		SFSBuffers::iterator iter = mSFSBuffers.begin(), end = mSFSBuffers.end();
		while (iter != end)
		{
			CELL_DELETE iter->second;
			++iter;
		}

		mSFSBuffers.clear();
	}
}
//---------------------------------------------------------------------------
const String& SingleFileStorage::getTypeName(void) const
{
	return SingleFileStorageFactory::FACTORY_TYPE_NAME;
}
//---------------------------------------------------------------------------
bool SingleFileStorage::open(const String& filename)
{
	CELL_LOCK_MUTEX(mMonitor);

	// 打开同一个文件
	if (mFileName == filename)
		return true;

	// 已经打开
	if (mFileName.length() > 0)
		return false;

	mFileName = filename;
	return true;
}
//---------------------------------------------------------------------------
void SingleFileStorage::close(void)
{
	CELL_LOCK_MUTEX(mMonitor);

	if (!mSFSBuffers.empty())
	{
		std::vector<SFSBuffer*> buffers;
		SFSBuffers::iterator iter = mSFSBuffers.begin(), end = mSFSBuffers.end();
		while (iter != end)
		{
			buffers.push_back(iter->second);
			++iter;
		}

		// 按照写入位置排序
		std::sort(buffers.begin(), buffers.end(), SFSBuffer::compare);
		// 合并并写入数据
		mergeAndFlushBuffer(buffers);
	}

	mFileName = "";
	mFileSize = 0;
	mTotalLength = 0;

	if (NULL != mReadBuffer)
	{
		CELL_DELETE mReadBuffer;
		mReadBuffer = NULL;
	}
}
//---------------------------------------------------------------------------
ResultSet* SingleFileStorage::createResultSet(void)
{
	return CELL_NEW SingleFileResultSet();
}
//---------------------------------------------------------------------------
void SingleFileStorage::destroyResultSet(ResultSet* resultSet)
{
	CELL_DELETE dynamic_cast<SingleFileResultSet*>(resultSet);
}
//---------------------------------------------------------------------------
void SingleFileStorage::store(ResultSet* resultSet, const String& statement)
{
	CELL_LOCK_MUTEX(mMonitor);

	if (mFileName.length() == 0)
	{
		return;
	}

	if (statement == "read")
	{
		// 读取文件
		if (read())
		{
			SingleFileResultSet* sfrs = dynamic_cast<SingleFileResultSet*>(resultSet);
			sfrs->fill(this, statement, mFileName, mFileSize);
			sfrs->copyFileData(mReadBuffer, 0, mReadBuffer->capacity());
		}
	}
	else if (statement == "write")
	{
		SingleFileResultSet* sfrs = dynamic_cast<SingleFileResultSet*>(resultSet);
		sfrs->fill(this, statement, mFileName, mFileSize);
	}
}
//---------------------------------------------------------------------------
void SingleFileStorage::store(ResultSet* resultSet, const Schema* schema)
{
	// Nothing
}
//---------------------------------------------------------------------------
void SingleFileStorage::setFetchSize(uint size)
{
	CELL_LOCK_MUTEX(mMonitor);

	if ((size & (size - 1)) == 0)
	{
		mFetchSize = size;
	}
}
//---------------------------------------------------------------------------
uint SingleFileStorage::getFetchSize(void) const
{
	CELL_LOCK_MUTEX(mMonitor);
	return mFetchSize;
}
//---------------------------------------------------------------------------
void SingleFileStorage::setMaxFetchNum(int num)
{
	CELL_LOCK_MUTEX(mMonitor);

	if (num <= 0)
	{
		return;
	}

	mMaxFetchNum = num;
}
//---------------------------------------------------------------------------
int SingleFileStorage::getMaxFetchNum(void) const
{
	CELL_LOCK_MUTEX(mMonitor);
	return mMaxFetchNum;
}
//---------------------------------------------------------------------------
String SingleFileStorage::getReadStatement(void)
{
	String statement("read");
	return statement;
}
//---------------------------------------------------------------------------
String SingleFileStorage::getWriteStatement(void)
{
	String statement("write");
	return statement;
}
//---------------------------------------------------------------------------
void SingleFileStorage::changeSize(int64 size)
{
	CELL_LOCK_MUTEX(mMonitor);

	if (mFileSize == size)
	{
		return;
	}

	mFileSize = size;
}
//---------------------------------------------------------------------------
bool SingleFileStorage::read(void)
{
	if (0 == mFileSize)
	{
		// 获取文件大小
		mFileSize = FileUtil::fileSize(mFileName);

		// 文件不存在，读取失败
		if (0 == mFileSize)
		{
			return false;
		}
	}

	if (mFileSize <= (int64)mFetchSize)
	{
		if (NULL == mReadBuffer)
		{
			// 创建 Buffer
			mReadBuffer = CELL_NEW CharBuffer(mFileSize);
			char buf[SFS_BUFFER_SIZE] = {0x0};

			/* 以下代码仅测试用
			std::ifstream file(mFileName, std::ios::binary);
			while (!file.eof())
			{
				file.read(buf, sizeof(buf));
				mReadBuffer->put(buf, file.gcount());
			}
			file.close();
			*/

			FILE* fp = fopen(mFileName.c_str(), "rb");
			int len = 0;
			while ((len = fread(buf, 1, sizeof(buf), fp)) > 0)
			{
				mReadBuffer->put(buf, len);
			}
			fclose(fp);

			mReadBuffer->flip();
		}
	}
	else
	{
		// 文件大小超过截取值
		if (NULL == mReadBuffer)
		{
			// 创建 Buffer
			mReadBuffer = CELL_NEW CharBuffer(mFetchSize);
			char buf[SFS_BUFFER_SIZE] = {0x0};
			uint size = 0;

			/* 以下代码仅测试用
			std::ifstream file(mFileName, std::ios::binary);
			while (!file.eof())
			{
				file.read(buf, sizeof(buf));
				mReadBuffer->put(buf, file.gcount());

				size += file.gcount();
				if (size == mFetchSize)
					break;
			}
			file.close();
			*/

			FILE* fp = fopen(mFileName.c_str(), "rb");
			int len = 0;
			while ((len = fread(buf, 1, sizeof(buf), fp)) > 0)
			{
				mReadBuffer->put(buf, len);

				size += len;
				if (size == mFetchSize)
				{
					break;
				}
			}
			fclose(fp);

			mReadBuffer->flip();
		}
	}

	return true;
}
//---------------------------------------------------------------------------
void SingleFileStorage::write(char* src, int64 offset, int length)
{
	CELL_LOCK_MUTEX(mMonitor);

	SFSBuffer* buf = findBuffer(offset);

	if (buf->position() + length > buf->capacity())
	{
		// 数据大小超过缓冲区，拆分数据

		int num = (int)floor((float)length / (float)buf->capacity());
		int mod = length % buf->capacity();

		int64 offsetCount = offset - buf->filePosition();
		int srcOffset = 0;
		for (int i = 0; i < num; ++i)
		{
			if (buf == NULL)
			{
				buf = findBuffer(offsetCount);
			}

			buf->put(src + srcOffset, 0, buf->capacity());
			srcOffset += buf->capacity();
			offsetCount += buf->capacity();

			buf = NULL;
		}

		buf = findBuffer(offsetCount);
		buf->put(src + srcOffset, 0, mod);
	}
	else
	{
		buf->put(src, offset - buf->filePosition(), length);
	}

	mTotalLength += length;

	checkFlush();
}
//---------------------------------------------------------------------------
SFSBuffer* SingleFileStorage::findBuffer(int64 offset)
{
	if (mSFSBuffers.empty())
	{
		SFSBuffer* buffer = CELL_NEW SFSBuffer(offset, mFetchSize);
		mSFSBuffers.insert(SFSBuffers::value_type(offset, buffer));
		return buffer;
	}

	SFSBuffers::iterator iter = mSFSBuffers.begin(), end = mSFSBuffers.end();
	while (iter != end)
	{
		int64 start = iter->first;
		SFSBuffer* buffer = iter->second;
		int64 end = start + buffer->capacity();
		if (offset >= start && offset < end)
		{
			return buffer;
		}

		++iter;
	}

	SFSBuffer* buffer = CELL_NEW SFSBuffer(offset, mFetchSize);
	mSFSBuffers.insert(SFSBuffers::value_type(offset, buffer));
	return buffer;
}
//---------------------------------------------------------------------------
void SingleFileStorage::flushBuffer(SFSBuffer* buffer)
{
	buffer->flip();

	// 获取缓存内数据
	char* fd = CELL_ALLOC_T(char, buffer->limit(), MEMCATEGORY_GENERAL);
	memset(fd, 0x0, buffer->limit());
	int length = buffer->get(fd);

	/* 以下代码仅测试用
	std::ofstream file(mFileName, std::ios::binary | std::ios::app);
	file.seekp(buffer->filePosition(), std::ios::beg);
	file.write(fd, length);
	file.flush();
	file.close();
	*/

	FILE* fp = fopen(mFileName.c_str(), "wb");
	fseek(fp, buffer->filePosition(), SEEK_SET);
	fwrite(fd, 1, length, fp);
	fclose(fp);

	CELL_FREE(fd, MEMCATEGORY_GENERAL);

	SFSBuffers::iterator iter = mSFSBuffers.find(buffer->filePosition());
	mSFSBuffers.erase(iter);
	CELL_DELETE buffer;
}
//---------------------------------------------------------------------------
void SingleFileStorage::mergeAndFlushBuffer(const std::vector<SFSBuffer*>& list)
{
	SFSBuffer* buf = NULL;
	int64 totalSize = 0;
	std::vector<SFSBuffer*>::const_iterator iter = list.begin(), end = list.end();
	while (iter != end)
	{
		buf = (*iter);
		buf->flip();
		totalSize += buf->limit();
		++iter;
	}

	char* fd = CELL_ALLOC_T(char, totalSize, MEMCATEGORY_GENERAL);
	memset(fd, 0x0, totalSize);

	int lenCount = 0;
	iter = list.begin();
	end = list.end();
	while (iter != end)
	{
		buf = (*iter);
		int len = buf->get(fd + lenCount);

		lenCount += len;
		++iter;
	}

	// 取第一个 Buffer，获取起始位置
	buf = (*list.begin());

	/* 以下代码仅测试用
	std::ofstream file(mFileName, std::ios::binary | std::ios::app);
	file.seekp(buf->filePosition(), std::ios::beg);
	file.write(fd, totalSize);
	file.flush();
	file.close();
	*/

	FILE* fp = fopen(mFileName.c_str(), "wb");
	fseek(fp, buf->filePosition(), SEEK_SET);
	fwrite(fd, 1, totalSize, fp);
	fclose(fp);

	CELL_FREE(fd, MEMCATEGORY_GENERAL);

	// 清空缓存
	iter = list.begin();
	end = list.end();
	while (iter != end)
	{
		buf = (*iter);
		SFSBuffers::iterator sfsb = mSFSBuffers.find(buf->filePosition());
		mSFSBuffers.erase(sfsb);
		CELL_DELETE buf;
		++iter;
	}
}
//---------------------------------------------------------------------------
void SingleFileStorage::checkFlush(void)
{
	if (mFileSize == 0)
	{
		return;
	}

	// 判断缓存数量是否达到最大值
	if (mSFSBuffers.size() >= (size_t) mMaxFetchNum)
	{
		std::vector<SFSBuffer*> list;
		SFSBuffers::iterator iter = mSFSBuffers.begin(), end = mSFSBuffers.end();
		while (iter != end)
		{
			list.push_back(iter->second);
			++iter;
		}

		// 按照写入位置排序
		std::sort(list.begin(), list.end(), SFSBuffer::compare);
		// 合并并压入数据
		mergeAndFlushBuffer(list);
	}

	if (mTotalLength == mFileSize && !mSFSBuffers.empty())
	{
		if (mSFSBuffers.size() > 1)
		{
			std::vector<SFSBuffer*> list;
			SFSBuffers::iterator iter = mSFSBuffers.begin(), end = mSFSBuffers.end();
			while (iter != end)
			{
				list.push_back(iter->second);
				++iter;
			}

			// 按照写入位置排序
			std::sort(list.begin(), list.end(), SFSBuffer::compare);

			// 合并并压入数据
			mergeAndFlushBuffer(list);
		}
		else
		{
			flushBuffer((mSFSBuffers.begin())->second);
		}
	}
}



//---------------------------------------------------------------------------
SFSBuffer::SFSBuffer(int64 position, int capacity)
	: CharBuffer(capacity)
	, mPosition(position)
{
}
//---------------------------------------------------------------------------
SFSBuffer::~SFSBuffer(void)
{
}
//---------------------------------------------------------------------------
FORCEINLINE int64 SFSBuffer::filePosition(void) const
{
	return mPosition;
}
//---------------------------------------------------------------------------
bool SFSBuffer::compare(const SFSBuffer* buf1, const SFSBuffer* buf2)
{
	return buf1->mPosition < buf2->mPosition;
}



//---------------------------------------------------------------------------
const String SingleFileStorageFactory::FACTORY_TYPE_NAME = "SingleFileStorage";

//---------------------------------------------------------------------------
SingleFileStorageFactory::SingleFileStorageFactory(void)
{
}
//---------------------------------------------------------------------------
SingleFileStorageFactory::~SingleFileStorageFactory(void)
{
}
//---------------------------------------------------------------------------
Storage* SingleFileStorageFactory::createInstance(const String& instanceName)
{
	return CELL_NEW SingleFileStorage(instanceName);
}
//---------------------------------------------------------------------------
void SingleFileStorageFactory::destroyInstance(Storage* instance)
{
	CELL_DELETE dynamic_cast<SingleFileStorage*>(instance);
}
//---------------------------------------------------------------------------
void SingleFileStorageFactory::initMetaData(void) const
{
	mMetaData.typeName = FACTORY_TYPE_NAME;
	mMetaData.description = "Single File Storage";
	mMetaData.storageTypeMask = ST_SINGLE_FILE;
}
} // end namespace cell
